package com.wjv.example.spbt.shiro.controller;

import com.wjv.example.common.ResultInfo;
import com.wjv.example.spbt.shiro.model.UserInfo;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

/**
 * <p>Title: AuthController</p>
 *
 * @author wjv
 * @date 2021/7/5 14:34
 */
@RestController
@RequestMapping("/auth")
public class AuthController {

    /**
     * 登录
     *
     * @param username
     * @param pwd
     * @return
     */
    @GetMapping("/login")
    public ResultInfo login(String username, String pwd) {
        Subject subject = SecurityUtils.getSubject();

        // 如果已经登录过，就直接返回。
        if (subject.isAuthenticated()) {
            System.out.println("已经登录过...");
            Map<String, Object> result = getUser(subject);
            return ResultInfo.success(result);
        }

        try {
            subject.login(new UsernamePasswordToken(username, pwd));
        } catch (AuthenticationException ae) {
            return ResultInfo.fail("认证失败");
        }

        Map<String, Object> result = getUser(subject);
        return ResultInfo.success(result);
    }

    private Map<String, Object> getUser(Subject subject) {
        UserInfo userInfo = (UserInfo) subject.getPrincipal();
        Map<String, Object> result = new HashMap<>();
        result.put("userName", userInfo.getUserName());
        result.put("token", subject.getSession().getId());
        return result;
    }

    @GetMapping("/logout")
    public ResultInfo logout() {
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return ResultInfo.success("登出成功");
    }

    @GetMapping("/401")
    public ResultInfo p401() {
        return ResultInfo.fail("请登录");
    }

    @GetMapping("/403")
    public ResultInfo p403() {
        return ResultInfo.fail("权限不足");
    }
}
